const WXAPI = require('../../Wxapi/api.js')
Component({
  properties: {
    
  },
  data: {
    // 这里是一些组件内部数据
    is_show: false,
    info: {} // 哪个页面调用的
  },
  methods: {
    // 这里放置自定义方法
    hideModel: function () {
      this.setData({
        is_show: true,
      })
    },
    showModel: function (e) {
      console.log(e)
      this.setData({
        is_show: false,
        info: e
      })
    },
    // 授权
    bindGetUserInfo:function(e){
      let that = this;
      if (e.detail.errMsg === "getUserInfo:fail auth deny") {
        // 回参
        that.triggerEvent('authorize', false)
      }
      that.login()
    },
    login: function () {
      let that = this;
      wx.login({
        success: function (res) {
          WXAPI.getUserInfo({
            code: res.code
          }).then(function (res) {
            if (res.code == 200) {
              console.log("用户已存在", res)
              wx.setStorageSync("uid", res.user_info.id);
              wx.setStorageSync("openId", res.user_info.openId)
              wx.getUserInfo({
                success: function (res) {
                  console.log("获取用户信息并设置缓存:", res.userInfo)
                  wx.setStorageSync("userInfo", res.userInfo)
                },
                complete:function(){
                  // 回参
                  this.triggerEvent('authorize', true)
                }
              })
            } else if (res.code == 201) {
              console.log("用户注册");
              // 注册用户
              that.registerUser(res.openId)
            }
          })
        }
      })
    },
    // 注册
    registerUser: function (openId) {
      let that = this;
      console.log("开始正式注册")
      wx.login({
        success: function (res) {
          let code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
          wx.getUserInfo({
            success: function (res) {
              let avatarUrl = res.userInfo.avatarUrl,
                nickName = res.userInfo.nickName,
                gender = res.userInfo.gender,
                country = res.userInfo.country,
                province = res.userInfo.province,
                city = res.userInfo.city
              // 下面开始调用注册接口
              WXAPI.register({
                avatarUrl: avatarUrl,
                nickName: nickName,
                openId: openId,
                gender: gender,
                country: country,
                province: province,
                city: city,
              }).then(function (res) {
                that.login()
              })
            }
          })
        }
      })
    }
  }
})